import { AUTH_KEY as key } from '@/constants'
const isBrowser = process.client
const Cookie = isBrowser ? require("js-cookie") : undefined

const userToken = {
  get() {
    return (Cookie && Cookie.get(key)) || ""
  },
  set(token = "") {
    if (Cookie) Cookie.set(key, token)
  },
  clear() {
    if (Cookie) Cookie.remove(key)
  },
}

export default {
  get() {
    if (!isBrowser) return {}
    try {
      const dataStr = localStorage.getItem(key)
      if (!dataStr) return {}
      const { value, maxAge, timestamp } = JSON.parse(dataStr)
      const data = maxAge + timestamp > Date.now() ? value : {}
      if (!data) localStorage.removeItem(key) // 超时删除缓存
      return data
    } catch (e) {
      localStorage.removeItem(key)
      return {}
    }
  },
  set(value = {}, maxAge = 60 * 24 * 10) {
    if (value.token) userToken.set(value.token)
    if (!isBrowser) return
    const data = {
      value: { ...this.get(), ...value },
      maxAge: maxAge * 60000,
      timestamp: new Date().getTime()
    }
    localStorage.setItem(key, JSON.stringify(data))
  },
  clear() {
    userToken.clear()
    if (!isBrowser) return
    const { time = 0 } = this.get()
    localStorage.removeItem(key)
    this.set({ time })
  }
}
